package logic

import (
	"context"
	"errors"
	"hm-fresh-api/models/mysql"

	"hm-fresh-api/freshrpc/freshrpc"
	"hm-fresh-api/freshrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshAddLogic {
	return &FreshAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品创建
func (l *FreshAddLogic) FreshAdd(in *freshrpc.FreshAddRequest) (*freshrpc.FreshAddResponse, error) {
	// todo: add your logic here and delete this line

	var findFresh mysql.Fresh

	if err := findFresh.FindFreshByTitle(mysql.DB, in.Title); err == nil {
		return nil, errors.New("商品已存在")
	}

	var class mysql.Class

	if err := class.FindClassByTitle(mysql.DB, in.ClassName); err != nil {
		class = mysql.Class{
			Name: in.ClassName,
		}

		if err := class.ClassAdd(mysql.DB); err != nil {
			return nil, errors.New("商品分类添加失败")
		}
	}

	fresh := mysql.Fresh{
		Title: in.Title,
		Price: float64(in.Price),
		//SortId:  in.SortId,
		ClassId: int64(class.ID),
	}

	err := fresh.FreshAdd(mysql.DB)
	if err != nil {
		return nil, err
	}

	return &freshrpc.FreshAddResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
